import { toolAdd, toolDel, toolPage, toolUpdate } from "@/api/baseData/tooling"
import type { FormInstance, FormRules } from "element-plus"
import { ElMessage } from "element-plus"
import { onMounted, ref } from "vue"

interface toolRecord {
  extension?: Record<string, any>
  id: string
  createTime?: string
  updateUser?: string
  updateTime?: string
  createUser?: string
  toolingCode: string
  toolingType: string
  toolingInventoryType?: string // 新建字段
  description?: string
  activate?: boolean
  isDeleted?: boolean
  clazz?: string
}

interface toolPageResult {
  records: toolRecord[]
  total: number
  size: number
  current: number
  optimizeCountSql: boolean
  searchCount: boolean
  pageSize: number
}

interface ApiResponse<T> {
  code: number
  message: string
  data: T
}

interface PaginationParams {
  current: number
  pageSize: number
}

interface FormData {
  toolingCode: string
  toolingType: string
  toolingInventoryType: string
}

export function useToolData() {
  const searchParam = ref({})
  const isLoading = ref(true)
  const searchFields = ref([
    {
      name: "toolRegisterCode",
      label: "工装编码",
      component: "input",
      placeholder: "",
      class: "!w-[350px]",
    },
    {
      name: "registerName",
      label: "工装名称",
      component: "input",
      placeholder: "",
      class: "!w-[350px]",
    },
  ])
  const pageTotal = ref(0)
  const paginatedData = ref<toolRecord[]>([])
  const paginationParams = ref<PaginationParams>({ current: 1, pageSize: 10 })
  const formData = ref<FormData>({
    toolingCode: "",
    toolingType: "",
    toolingInventoryType: "",
  })

  const ruleFormRef = ref<FormInstance>() // 表单实例引用

  const rules = ref<FormRules<FormData>>({
    toolRegisterCode: [{ required: true, message: "请输入工装编码", trigger: "blur" }],
    registerName: [{ required: true, message: "请输入工装名称", trigger: "blur" }],
    toolId: [{ required: true, message: "请选择工装类型", trigger: "blur" }],
    no: [{ required: true, message: "请输入模具代号", trigger: "blur" }],
  })
  const fetchPageData = async (params: any) => {
    isLoading.value = true
    try {
      const response = (await toolPage({
        ...params,
        current: paginationParams.value.current,
        pageSize: paginationParams.value.pageSize,
      })) as unknown as ApiResponse<toolPageResult>

      if (response.code === 200) {
        const { records, total } = response.data
        paginatedData.value = records.map((item) => {
          return {
            ...item.extension,
            ...item,
          }
        })
        pageTotal.value = total
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error("数据获取失败")
    } finally {
      isLoading.value = false // 数据加载完成后设置为 false
    }
  }

  onMounted(() => {
    fetchPageData(searchParam.value)
  })

  const handleSearch = () => {
    fetchPageData(searchParam.value)
  }

  const handleSizeChange = (val: number) => {
    paginationParams.value.pageSize = val
    fetchPageData(searchParam.value)
  }

  const handleCurrentChange = (val: number) => {
    paginationParams.value.current = val
    fetchPageData(searchParam.value)
  }

  const addTool = async (data: Partial<toolRecord>, callback: () => void) => {
    if (ruleFormRef.value) {
      await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
          const url = data?.id ? toolUpdate : toolAdd
          const response = (await url(data)) as unknown as ApiResponse<void>
          if (response.code === 200) {
            if (data?.id) {
              ElMessage.success("更新成功")
            } else {
              ElMessage.success("添加成功")
            }
            fetchPageData(searchParam.value)
            callback()
          } else {
            ElMessage.error(response.message)
          }
        }
      })
    }
  }

  const deleteTool = async (id: string) => {
    try {
      const response = (await toolDel({ ids: [id] })) as unknown as ApiResponse<void>
      if (response.code === 200) {
        ElMessage.success("删除成功")
        fetchPageData(searchParam.value)
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error("删除失败")
    }
  }

  return {
    searchParam,
    pageTotal,
    paginatedData,
    searchFields,
    isLoading,
    handleSearch,
    handleSizeChange,
    handleCurrentChange,
    addTool,
    deleteTool,
    paginationParams,
    ruleFormRef,
    rules,
    formData,
  }
}
